<?php
declare(strict_types=1);

namespace Zms\HyperfCasts;

use Hyperf\Contract\CastsAttributes;


/**
 * IP储存转换器,转换为二进制地址
 * Class ArrjoinCasts
 * @package Core\Casts
 */
class IpCasts implements CastsAttributes
{
    /**
     * 获取结果
     */
    public function get($model, $key, $value, $attributes)
    {
        if (gettype($value) === 'string' && strlen($value) > 0) {
            return inet_ntop($value) ?: '0.0.0.0';
        }
        return '0.0.0.0';
    }


    /**
     * 设置数据
     */
    public function set($model, $key, $value, $attributes)
    {
        if (filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
            return inet_pton($value);
        } elseif (filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
            return inet_pton($value);
        }
        return inet_pton('0.0.0.0');
    }
}
